import axios from 'axios';
import router from '@/router';

// axios.defaults.baseURL = 'http://192.168.31.120:8070/back/';//本地
axios.defaults.baseURL = 'https://topp.ymtykj.com/back/';//服务器
// axios.defaults.baseURL = 'http://61.188.39.17:8070/back/';//测试服

axios.defaults.withCredentials = true;       
// 发送请求前处理request的数据
axios.defaults.transformRequest = [function (data) {
  if(data instanceof FormData){
    return data;
  }else{
    let newData = ''
    for (let k in data) {
    newData += encodeURIComponent(k) + '=' + encodeURIComponent(data[k]) + '&'
    }
    return newData
  }
}]    

// http request 拦截器
axios.interceptors.request.use(
  config => {
    // const token = getCookie('名称');注意使用的时候需要引入cookie方法，推荐js-cookie
    // config.data = JSON.stringify(config.data);
    config.headers = {
      'Content-Type':'application/x-www-form-urlencoded'
    }
    // if(token){
    //   config.params = {'token':token}
    // }
    return config;
  },
  error => {
    return Promise.reject(err);
  }
);
  
//http response 拦截器
axios.interceptors.response.use(
    response => {
      //-1超时 0有误 1成功
      if(response.data.result==1){
        return Promise.resolve(response.data);
      }else if(response.data.result == -1){
        router.push({
          path:"/Login",
          query:{redirect:router.currentRoute.fullPath}//从哪个页面跳转
        })
        return Promise.reject(response.data.msg)
      }else{
        return Promise.reject(response.data.msg)
      }
    },
    error => {
      return Promise.reject('网络有误')
    }
)